# coding:utf-8
import base64
from crypt import methods
import datetime
import json
import os
import random
import re
import time
from datetime import date
import uuid
from io import BytesIO

import requests
from flask import Blueprint, render_template, request, redirect, url_for, flash, session, jsonify, app, make_response, \
    current_app
from sqlalchemy import or_
from werkzeug.utils import secure_filename

import urllib
from App.ext import db, socketio
from App.validate_code import get_verify_code
from .models import Discuss
from datetime import timedelta

# 查询商品信息
from App.ShowapiRequest import ShowapiRequest
import json

discuss = Blueprint('discuss', __name__)

@discuss.route('/createAll')
def create():
    db.create_all()
    return 'ok'

@discuss.route('/getAllDiscuss', methods=['GET'])
def check():
    if request.method == "GET":
        username=request.args.get('username')
        password=request.args.get('password')
        # 校验
         # 核对用户名和密码是否一致
        user = User.query.filter_by(username=username, password=password, user_status=1).first()
        # 如果用户名和密码一致
        if user:
            # 向session中写入相应的数据
            session['user_id'] = user.user_id
            session['username'] = user.username
            session['user_pic'] = user.Icon
            msg = '* 校验通过'
            return jsonify({'code': 0, 'msg': msg, 'succ': True, 'username': username})
        # 如果用户名和密码不一致返回登录页面,并给提示信息
        else:
            msg = '* 用户名或者密码不一致'
            return jsonify({'code': 0, 'msg': msg, 'succ': False})

# 添加讨论
@discuss.route('/add', methods=['GET', 'POST'])
def register():
    print("method: ", request.method)
    print("request.content_type: ", request.content_type)
    if request.method == "POST":
        if request.content_type.startswith('application/x-www-form-urlencoded'):            
            username=request.args.get('username')
            password=request.args.get('password')
            # 校验
            # 核对用户名和密码是否一致
            user = User.query.filter_by(username=username, password=password, user_status=1).first()
            # 如果用户名和密码一致
            if user:
                # 向session中写入相应的数据
                discuss = Discuss(username = username)
                discuss.price = request.args.get('username')
                discuss.content =  request.args.get('content')
                discuss.image_url =  request.args.get('image_url')
                discuss.update_time = request.args.get('update_time') 
                discuss.phone = request.args.get('phone')
                db.session.add(discuss)
                db.session.commit()
                return jsonify({'code': 0, 'msg': "保存成功", 'succ': True, 'username': username})
        # 如果用户名和密码不一致返回登录页面,并给提示信息 